package com.bieber.smartpost.invoke.filter;

import com.bieber.smartpost.env.EnvironmentFacade;
import com.bieber.smartpost.invoke.FilterChain;
import com.bieber.smartpost.model.RequestEntity;
import com.jbeer.framework.annotation.Bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by bieber on 2014/11/12.
 */
@Bean
public class EnvironmentFilter extends AbstractFilter {
    private static final Pattern ENV_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{[\\w]{1,}\\}");

    public void doFilter(FilterChain chain, RequestEntity entity) {
        String url = entity.getUrl();
        entity.setUrl(getEnv(url,entity.getEnvId()));

        if(entity.getHeader()!=null){
            for(Map<String,String> header:entity.getHeader()){
                for(Map.Entry<String,String> entry:header.entrySet()){
                    header.put(entry.getKey(),getEnv(entry.getValue(),entity.getEnvId()));
                }
            }
        }

        if(entity.getParams()!=null){
            if(String.class.isAssignableFrom(entity.getParams().getClass())){
                entity.setParams(getEnv(entity.getParams().toString(),entity.getEnvId()));
            }else if(List.class.isAssignableFrom(entity.getParams().getClass())){
                List<Map<String,String>> params = (List<Map<String, String>>) entity.getParams();
                for(Map<String,String> param:params){
                    for(Map.Entry<String,String> entry:param.entrySet()){
                        param.put(entry.getKey(),getEnv(entry.getValue(),entity.getEnvId()));
                    }
                }
            }
        }
        chain.doChain(entity);
    }



    private static String getEnv(String marchedString,String envId){
        Matcher urlMatcher = ENV_PLACEHOLDER_PATTERN.matcher(marchedString);
        StringBuffer result = new StringBuffer(marchedString);
        List<String> values = new ArrayList<String>();
        while(urlMatcher.find()){
            String group = urlMatcher.group();
            String envValue = EnvironmentFacade.getEnv(group,envId);
            values.add(envValue);
        }
        String holder = urlMatcher.replaceAll("%s");
        return  String.format(holder, values.toArray());
    }

    public int order() {
        return 0;
    }

}
